<template>
  <div class="app-container">
    <div ref="threeContainer" class="canvas-container"></div>

    <div class="stars">
      <div
          v-for="(star, index) in stars"
          :key="index"
          class="star"
          :style="starStyle(star)"
      ></div>
    </div>

    <div class="login-container">
      <div class="logo">
        <h1>天机罗盘</h1>
        <p>探索未知，预知未来</p>
      </div>

      <div class="character">
        <img :src="characterImage" alt="Q版占卜师">
      </div>

      <div class="tabs">
        <div
            class="tab"
            :class="{ active: activeTab === 'login' }"
            @click="switchTab('login')"
        >
          登录
        </div>
        <div
            class="tab"
            :class="{ active: activeTab === 'register' }"
            @click="switchTab('register')"
        >
          注册
        </div>
      </div>

      <!-- 登录表单 -->
      <div class="form-container" :class="{ active: activeTab === 'login' }">
        <div class="form-group">
          <label for="login-username">用户名</label>
          <input
              type="text"
              id="login-username"
              placeholder="请输入用户名"
              v-model="loginForm.username"
              @focus="clearError('loginUsername')"
          >
          <div class="error-message" v-if="errors.loginUsername">
            {{ errors.loginUsername }}
          </div>
        </div>
        <div class="form-group">
          <label for="login-password">密码</label>
          <input
              type="password"
              id="login-password"
              placeholder="请输入密码"
              v-model="loginForm.password"
              @focus="clearError('loginPassword')"
          >
          <div class="error-message" v-if="errors.loginPassword">
            {{ errors.loginPassword }}
          </div>
        </div>
        <button class="submit-btn" @click="handleLogin">登录</button>

        <div class="forgot-password">
          <a href="#" @click.prevent="handleForgotPassword">忘记密码？</a>
        </div>

<!--        <div class="divider">-->
<!--          <span>或使用以下方式登录</span>-->
<!--        </div>-->

<!--        <div class="social-login">-->
<!--          <button class="social-btn" @click="socialLogin('wechat')">微信</button>-->
<!--          <button class="social-btn" @click="socialLogin('qq')">QQ</button>-->
<!--          <button class="social-btn" @click="socialLogin('weibo')">微博</button>-->
<!--        </div>-->
      </div>

      <!-- 注册表单 -->
      <div class="form-container" :class="{ active: activeTab === 'register' }">
        <div class="form-group">
          <label for="register-username">用户名</label>
          <input
              type="text"
              id="register-username"
              placeholder="请输入用户名"
              v-model="registerForm.username"
              @focus="clearError('registerUsername')"
          >
          <div class="error-message" v-if="errors.registerUsername">
            {{ errors.registerUsername }}
          </div>
        </div>
        <div class="form-group">
          <label for="register-email">邮箱</label>
          <input
              type="email"
              id="register-email"
              placeholder="请输入邮箱"
              v-model="registerForm.email"
              @focus="clearError('registerEmail')"
          >
          <div class="error-message" v-if="errors.registerEmail">
            {{ errors.registerEmail }}
          </div>
        </div>
        <div class="form-group">
          <label for="register-password">密码</label>
          <input
              type="password"
              id="register-password"
              placeholder="请输入密码"
              v-model="registerForm.password"
              @focus="clearError('registerPassword')"
          >
          <div class="error-message" v-if="errors.registerPassword">
            {{ errors.registerPassword }}
          </div>
        </div>
        <div class="form-group">
          <label for="register-confirm-password">确认密码</label>
          <input
              type="password"
              id="register-confirm-password"
              placeholder="请再次输入密码"
              v-model="registerForm.confirmPassword"
              @focus="clearError('registerConfirmPassword')"
          >
          <div class="error-message" v-if="errors.registerConfirmPassword">
            {{ errors.registerConfirmPassword }}
          </div>
        </div>
        <button class="submit-btn" @click="handleRegister">注册</button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'

export default {
  name: 'LoginPage',
  setup() {
    // 响应式数据
    const activeTab = ref('login')
    const threeContainer = ref(null)

    const loginForm = reactive({
      username: '',
      password: ''
    })

    const registerForm = reactive({
      username: '',
      email: '',
      password: '',
      confirmPassword: ''
    })

    const errors = reactive({})

    const stars = ref([])
    const characterImage = ref("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 200 200'%3E%3Ccircle cx='100' cy='80' r='40' fill='%239d8aff'/%3E%3Ccircle cx='100' cy='200' r='70' fill='%237b61ff'/%3E%3Ccircle cx='75' cy='70' r='10' fill='white'/%3E%3Ccircle cx='125' cy='70' r='10' fill='white'/%3E%3Cpath d='M 80 100 Q 100 120 120 100' stroke='white' stroke-width='5' fill='none'/%3E%3C/svg%3E")

    // Three.js相关变量
    let scene, camera, renderer, particlesMesh, torus
    let THREE = null

    // 方法
    const switchTab = (tab) => {
      activeTab.value = tab
      clearErrors()
    }

    const validateLogin = () => {
      clearErrors()
      let isValid = true

      if (!loginForm.username.trim()) {
        errors.loginUsername = '请输入用户名'
        isValid = false
      }

      if (!loginForm.password) {
        errors.loginPassword = '请输入密码'
        isValid = false
      }

      return isValid
    }

    const validateRegister = () => {
      clearErrors()
      let isValid = true

      if (!registerForm.username.trim()) {
        errors.registerUsername = '请输入用户名'
        isValid = false
      }

      if (!registerForm.email.trim()) {
        errors.registerEmail = '请输入邮箱'
        isValid = false
      } else if (!/\S+@\S+\.\S+/.test(registerForm.email)) {
        errors.registerEmail = '请输入有效的邮箱地址'
        isValid = false
      }

      if (!registerForm.password) {
        errors.registerPassword = '请输入密码'
        isValid = false
      } else if (registerForm.password.length < 6) {
        errors.registerPassword = '密码长度至少6位'
        isValid = false
      }

      if (!registerForm.confirmPassword) {
        errors.registerConfirmPassword = '请确认密码'
        isValid = false
      } else if (registerForm.password !== registerForm.confirmPassword) {
        errors.registerConfirmPassword = '两次输入的密码不一致'
        isValid = false
      }

      return isValid
    }

    const handleLogin = () => {
      if (validateLogin()) {
        // 模拟登录API调用
        console.log('登录信息:', loginForm)
        alert('登录成功！')
        // 实际应用中这里会调用登录API
      }
    }

    const handleRegister = () => {
      if (validateRegister()) {
        // 模拟注册API调用
        console.log('注册信息:', registerForm)
        alert('注册成功！')
        // 实际应用中这里会调用注册API
      }
    }

    const handleForgotPassword = () => {
      alert('忘记密码功能开发中...')
    }

    const socialLogin = (platform) => {
      alert(`正在通过${platform}登录...`)
    }

    const clearErrors = () => {
      Object.keys(errors).forEach(key => {
        errors[key] = ''
      })
    }

    const clearError = (field) => {
      if (errors[field]) {
        errors[field] = ''
      }
    }

    const starStyle = (star) => {
      return {
        width: `${star.size}px`,
        height: `${star.size}px`,
        left: `${star.x}%`,
        top: `${star.y}%`,
        animationDelay: `${star.delay}s`
      }
    }

    // Three.js 3D背景
    const initThreeJS = async () => {
      // 动态导入Three.js
      try {
        // 检查是否在浏览器环境中
        if (typeof window !== 'undefined') {
          // 动态导入Three.js
          const threeModule = await import('three')
          THREE = threeModule.default || threeModule

          // 创建场景、相机和渲染器
          scene = new THREE.Scene()
          camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
          renderer = new THREE.WebGLRenderer({ alpha: true })

          renderer.setSize(window.innerWidth, window.innerHeight)
          renderer.setClearColor(0x261747, 0)
          threeContainer.value.appendChild(renderer.domElement)

          // 创建粒子系统
          const particlesGeometry = new THREE.BufferGeometry()
          const particlesCount = 5000

          const posArray = new Float32Array(particlesCount * 3)

          for (let i = 0; i < particlesCount * 3; i++) {
            posArray[i] = (Math.random() - 0.5) * 10
          }

          particlesGeometry.setAttribute('position', new THREE.BufferAttribute(posArray, 3))

          // 创建材质
          const particlesMaterial = new THREE.PointsMaterial({
            size: 0.005,
            color: 0x7b61ff,
            transparent: true,
            opacity: 0.8
          })

          // 创建粒子系统
          particlesMesh = new THREE.Points(particlesGeometry, particlesMaterial)
          scene.add(particlesMesh)

          // 创建旋转的几何体
          const geometry = new THREE.TorusGeometry(1, 0.4, 16, 100)
          const material = new THREE.MeshBasicMaterial({
            color: 0x9d8aff,
            wireframe: true,
            transparent: true,
            opacity: 0.3
          })
          torus = new THREE.Mesh(geometry, material)
          scene.add(torus)

          // 设置相机位置
          camera.position.z = 2

          // 动画循环
          const animate = () => {
            requestAnimationFrame(animate)

            particlesMesh.rotation.y += 0.001
            torus.rotation.x += 0.01
            torus.rotation.y += 0.005

            renderer.render(scene, camera)
          }

          animate()
        }
      } catch (error) {
        console.error('Three.js加载失败:', error)
        // 如果Three.js加载失败，显示备用背景
        threeContainer.value.innerHTML = '<div class="fallback-background"></div>'
      }
    }

    // 创建星空背景
    const createStars = () => {
      const starCount = 150
      stars.value = []

      for (let i = 0; i < starCount; i++) {
        stars.value.push({
          size: Math.random() * 3,
          x: Math.random() * 100,
          y: Math.random() * 100,
          delay: Math.random() * 5
        })
      }
    }

    // 响应窗口大小变化
    const handleResize = () => {
      if (camera && renderer) {
        camera.aspect = window.innerWidth / window.innerHeight
        camera.updateProjectionMatrix()
        renderer.setSize(window.innerWidth, window.innerHeight)
      }
    }

    // 生命周期钩子
    onMounted(() => {
      createStars()
      initThreeJS()
      window.addEventListener('resize', handleResize)
    })

    onBeforeUnmount(() => {
      // 清理Three.js资源
      if (renderer) {
        window.removeEventListener('resize', handleResize)
        renderer.dispose()
      }
    })

    return {
      activeTab,
      threeContainer,
      loginForm,
      registerForm,
      errors,
      stars,
      characterImage,
      switchTab,
      handleLogin,
      handleRegister,
      handleForgotPassword,
      socialLogin,
      clearError,
      starStyle
    }
  }
}
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Microsoft YaHei', sans-serif;
}

.app-container {
  background-color: #261747;
  color: #e0d6ff;
  overflow: hidden;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

.canvas-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

.login-container {
  position: relative;
  z-index: 2;
  width: 400px;
  background: rgba(38, 23, 71, 0.1);
  backdrop-filter: blur(5px);
  border-radius: 20px;
  padding: 30px;
  box-shadow: 0 0 30px rgba(123, 97, 255, 0.3);
  border: 1px solid rgba(123, 97, 255, 0.2);
  animation: glow 4s infinite alternate;
}

@keyframes glow {
  0% { box-shadow: 0 0 20px rgba(123, 97, 255, 0.3); }
  100% { box-shadow: 0 0 30px rgba(123, 97, 255, 0.6); }
}

.logo {
  text-align: center;
  margin-bottom: 20px;
}

.logo h1 {
  font-size: 32px;
  background: linear-gradient(90deg, #9d8aff, #c0b5ff);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  margin-bottom: 10px;
  text-shadow: 0 0 10px rgba(157, 138, 255, 0.5);
}

.logo p {
  font-size: 14px;
  color: #a89de0;
}

.character {
  text-align: center;
  margin: 20px 0;
  position: relative;
}

.character img {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid rgba(123, 97, 255, 0.5);
  animation: float 6s ease-in-out infinite;
}

@keyframes float {
  0% { transform: translateY(0); }
  50% { transform: translateY(-10px); }
  100% { transform: translateY(0); }
}

.tabs {
  display: flex;
  margin-bottom: 20px;
  border-bottom: 1px solid rgba(123, 97, 255, 0.3);
}

.tab {
  flex: 1;
  text-align: center;
  padding: 10px;
  cursor: pointer;
  transition: all 0.3s;
  color: #a89de0;
}

.tab.active {
  color: #c0b5ff;
  border-bottom: 2px solid #7b61ff;
}

.form-container {
  display: none;
}

.form-container.active {
  display: block;
  animation: fadeIn 0.5s;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

.form-group {
  margin-bottom: 20px;
  position: relative;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  color: #c0b5ff;
}

.form-group input {
  width: 100%;
  padding: 12px 15px;
  background: rgba(38, 23, 71, 0.2);
  border: 1px solid rgba(123, 97, 255, 0.3);
  border-radius: 10px;
  color: #e0d6ff;
  outline: none;
  transition: all 0.3s;
}

.form-group input:focus {
  border-color: #7b61ff;
  box-shadow: 0 0 10px rgba(123, 97, 255, 0.3);
}

.form-group input::placeholder {
  color: #6d5ba8;
}

.submit-btn {
  width: 100%;
  padding: 12px;
  background: linear-gradient(90deg, #7b61ff, #9d8aff);
  border: none;
  border-radius: 10px;
  color: white;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
  margin-top: 10px;
}

.submit-btn:hover {
  background: linear-gradient(90deg, #6a50e6, #8c7ae6);
  box-shadow: 0 0 15px rgba(123, 97, 255, 0.5);
}

.forgot-password {
  text-align: right;
  margin-top: 15px;
}

.forgot-password a {
  color: #a89de0;
  text-decoration: none;
  font-size: 14px;
}

.forgot-password a:hover {
  color: #c0b5ff;
}

.divider {
  display: flex;
  align-items: center;
  margin: 20px 0;
}

.divider::before,
.divider::after {
  content: "";
  flex: 1;
  height: 1px;
  background: rgba(123, 97, 255, 0.3);
}

.divider span {
  padding: 0 15px;
  color: #a89de0;
  font-size: 14px;
}

.social-login {
  display: flex;
  justify-content: space-between;
  gap: 10px;
}

.social-btn {
  flex: 1;
  padding: 10px;
  border: 1px solid rgba(123, 97, 255, 0.3);
  border-radius: 10px;
  background: rgba(38, 23, 71, 0.5);
  color: #c0b5ff;
  cursor: pointer;
  transition: all 0.3s;
  text-align: center;
}

.social-btn:hover {
  background: rgba(123, 97, 255, 0.2);
  border-color: #7b61ff;
}

.stars {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  pointer-events: none;
  z-index: 1;
}

.star {
  position: absolute;
  background-color: white;
  border-radius: 50%;
  animation: twinkle 5s infinite;
}

@keyframes twinkle {
  0%, 100% { opacity: 0.2; }
  50% { opacity: 1; }
}

.error-message {
  color: #ff6b6b;
  font-size: 12px;
  margin-top: 5px;
  text-align: left;
}

.fallback-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: radial-gradient(circle at 30% 30%, #3a2a6d, #261747);
  z-index: 1;
}
</style>